<template>
  <div>
    <Dialog
      ref="Drawer"
      @close="close"
      :loading="loading"
      @handleSave="handleSave"
      :title="title"
      :dialog="dialog"
      width="760px"
      :disabled="disabled"
    >
      <template #content>
        <el-form
          :disabled="disabled"
          :model="ruleForm"
          size="small"
          :rules="rules"
          ref="ruleForm"
          class="demo-ruleForm"
        >
          <el-form-item
            label="单位名称"
            prop="name"
          >
            <el-input
              v-model="ruleForm.name"
              placeholder="请输入单位名称"
            ></el-input>
          </el-form-item>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item
                label="简称"
                prop="shortName"
              >
                <el-input
                  v-model="ruleForm.shortName"
                  placeholder="请输入单位简称"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="医疗机构编码"
                prop="code"
              >
                <el-input
                  v-model="ruleForm.code"
                  placeholder="请输入医疗机构编码"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="医疗机构编号"
                prop="num"
              >
                <el-input
                  v-model="ruleForm.num"
                  disabled
                  placeholder="系统自动生成"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="企业信用代码"
                prop="creditCode"
              >
                <el-input
                  v-model="ruleForm.creditCode"
                  placeholder="请输入企业信用代码"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="省市区"
                prop="addressCode"
              >
                <tree-select
                  :data="treeData"
                  class="w100p"
                  :defaultProps="defaultProps"
                  :nodeKey="nodeKey"
                  ref="treeselect"
                  :checkedKeys="defaultCheckedKeys"
                  @popoverHide="popoverHide"
                ></tree-select>
                <!-- <el-cascader
              class="w100p"
              v-model="ruleForm.addressCode"
              clearable
              :props="props"
              placeholder="请选择省市区"
              @change="handleLocationsChange"
            ></el-cascader> -->
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="详细地址"
                prop="address"
              >
                <el-input
                  v-model="ruleForm.address"
                  placeholder="请输入详细地址"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item
                label="坐标位置"
                prop="address"
              >
                <div class="w100p s-d-inline-block">
                  <span class="mr10">X</span>
                  <el-input
                    readonly
                    class="w146"
                    v-model="ruleForm.longitude"
                    placeholder="请输入经度"
                  ></el-input>
                  <span class="ml20 mr10">Y</span>
                  <el-input
                    readonly
                    class="w146"
                    v-model="ruleForm.latitude"
                    placeholder="请输入纬度"
                  ></el-input>
                  <el-button
                    @click="handleInnerVisible"
                    type="text"
                  ><i class="el-icon-location-outline mr6 ml12"></i> 地图定位</el-button>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="管理员"
                v-if="title == '新增医院机构'"
                prop="adminName"
              >
                <el-input
                  v-model="ruleForm.adminName"
                  placeholder="请输入管理员姓名"
                ></el-input>
                <!-- <el-select
              class="w100p"
              v-model="ruleForm.adminName"
              placeholder="请选择管理员"
              @change="handleChooseAdmin()"
            >
              <el-option
                v-for="item in userList"
                :key="item.id"
                :label="item.name"
                :value="item.name"
              >
              </el-option>
            </el-select> -->
              </el-form-item>

            </el-col>
            <el-col :span="12">
              <el-form-item
                label="管理员电话"
                v-if="title == '新增医院机构'"
                prop="adminMobile"
              >
                <el-input
                  v-model="ruleForm.adminMobile"
                  placeholder="请输入管理员电话"
                ></el-input>
              </el-form-item>

            </el-col>
            <el-col :span="12">
              <el-form-item
                label="状态"
                prop="isFreeze"
              >
                <el-radio-group
                  class="w100p"
                  v-model="ruleForm.isFreeze"
                >
                  <el-radio :label="1">禁用</el-radio>
                  <el-radio :label="0">启用</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>

        </el-form>
        <el-dialog
          width="560px"
          title="坐标位置"
          append-to-body
          :visible.sync="innerVisible"
        >
          <BMap
            class="h390"
            ref="bmap"
            :disabled="disabled"
          ></BMap>
          <div
            slot="footer"
            class="dialog-footer"
          >
            <el-button
              type="primary"
              @click="handleSaveBmap()"
              size="small"
            ><i class="el-icon-circle-check ml0 mr10 el-icon--right"></i> 确 定</el-button>
            <el-button
              size="small"
              @click="innerVisible = false"
            ><i class="el-icon-circle-close ml0 mr10 el-icon--right"></i> 取 消</el-button>
          </div>
        </el-dialog>
      </template>

    </Dialog>
  </div>
</template>
<script>
import Dialog from "@/components/Dialog";
import * as hospitalApi from "@/api/hospital";
import * as areaApi from "@/api/area";
import { IdentityCodeValid } from "@/utils";
import { userList } from "@/api/setting1.js";
import AMap from "@/components/AMap/AMap.vue";
import BMap from "@/components/BMap/index.vue";
import TreeSelect from "@/components/TreeSelect";
import axios from "axios";
export default {
  components: {
    Dialog,
    AMap,
    BMap,
    TreeSelect,
  },
  data() {
    const validateUserName = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请输入管理员"));
      } else if (
        value &&
        !/^[A-Za-z0-9]{1,50}$|^[\u4e00-\u9fa5A-Za-z0-9]{1,25}$/.test(value)
      ) {
        callback(new Error("管理员名称不超过50个英文字符或25个汉字"));
      } else {
        callback();
      }
    };
    const validateUserPhone = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请输入管理员电话"));
      } else if (value && !/^1(3|4|5|6|7|8|9)\d{9}$/.test(value)) {
        callback(new Error("电话有误，请重填"));
      } else {
        callback();
      }
    };
    const validateCode = (rule, value, callback) => {
      {
        if (!value) {
          callback(new Error("请输入医疗机构编码"));
        } else if (value.length > 22) {
          callback(new Error("医疗机构编码长度小于22位"));
        } else {
          callback();
        }
      }
    };
    const validateCreditCode = (rule, value, callback) => {
      {
        if (!value) {
          callback(new Error("请输入企业信用代码"));
        } else if (value.length > 22) {
          callback(new Error("企业信用代码长度小于22位"));
        } else {
          callback();
        }
      }
    };
    const validateName = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请输入单位名称"));
      } else if (
        value &&
        !/^[A-Za-z0-9]{1,100}$|^[\u4e00-\u9fa5A-Za-z0-9]{1,50}$/.test(value)
      ) {
        callback(new Error("单位名称不超过100个英文字符或50个汉字"));
      } else {
        callback();
      }
    };
    const validateShortName = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请输入简称"));
      } else if (
        value &&
        !/^[A-Za-z0-9]{1,50}$|^[\u4e00-\u9fa5A-Za-z0-9]{1,25}$/.test(value)
      ) {
        callback(new Error("简称不超过50个英文字符或25个汉字"));
      } else {
        callback();
      }
    };
    const validateAddress = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请输入详细地址"));
      } else if (value && !/^[A-Za-z0-9]{1,100}$|^[\u4e00-\u9fa5A-Za-z0-9]{1,50}$/.test(value)) {
        callback(new Error("详细地址不超过100个英文字符或者50个汉字"));
      } else {
        callback();
      }
    };
    return {
      innerVisible: false,
      defaultProps: {
        children: "children",
        label: "name",
        isLeaf: false,
      },
      nodeKey: "code",
      defaultCheckedKeys: [],
      treeData: [],
      dialog: false, //弹框

      rules: {
        //form表单非空校验
        name: [
          {
            required: true,
            validator: validateName,
            trigger: "blur",
          },
        ],
        shortName: [
          {
            required: true,
            validator: validateShortName,
            trigger: "blur",
          },
        ],
        code: [
          {
            required: true,
            validator: validateCode,
            trigger: "blur",
          },
        ],
        creditCode: [
          {
            required: true,
            validator: validateCreditCode,
            trigger: "blur",
          },
        ],
        addressCode: [
          {
            required: true,
            message: "请选择省市区",
            trigger: "change",
          },
        ],
        address: [
          {
            required: true,
            validator:validateAddress,
            trigger: "blur",
          },
        ],
        adminName: [
          {
            required: true,
            validator: validateUserName,
            trigger: "blur",
          },
        ],
        adminMobile: [
          {
            required: true,
            validator: validateUserPhone,
            trigger: "blur",
          },
        ],
        longitude: [
          {
            required: true,
            message: "请选择经纬度",
            trigger: "blur",
          },
        ], //经纬度
      },
      props: {
        children: "children",
        lazy: true,
        async lazyLoad(node, resolve) {
          const { level } = node;
          if (level == 0) {
            //省
            const { data } = await areaApi.getProvinceList();
            var nodes = data.map((item) => {
              return {
                value: item.code,
                label: item.name,
                leaf: false,
              };
            });
            resolve(nodes);
          } else if (level == 1) {
            const { data } = await areaApi.getCityList({
              provinceCode: node.data.value,
            }); //获取市接口
            var nodes = data.map((item) => {
              return {
                value: item.code,
                label: item.name,
                leaf: false,
              };
            });
            resolve(nodes);
          } else if (level == 2) {
            const { data } = await areaApi.getRegionList({
              cityCode: node.data.value,
            }); //获取市接口
            var nodes = data.map((item) => {
              return {
                value: item.code,
                label: item.name,
                leaf: false,
              };
            });
            resolve(nodes);
          } else if (level == 3) {
            const { data } = await areaApi.getTownList({
              regionCode: node.data.value,
            }); //获取市接口
            var nodes = data.map((item) => {
              return {
                value: item.code,
                label: item.name,
                leaf: true,
              };
            });
            resolve(nodes);
          }
        },
      },
      ruleForm: {
        //表单提交
        address: "", //详细地址
        shortName: "", //简称
        adminMobile: "", //管理员电话
        adminName: "", //管理员名称
        cityCode: "", //市编码
        code: "", //医院编码
        creditCode: "", //信用代码
        id: "",
        adminId: "",
        num: "",
        addressCode: [],
        isFreeze: 1,
        name: "", //医院名称
        provinceCode: "", //省编码
        regionCode: "", //区编码
        townCode: "", //镇编码
        latitude: "",
        longitude: "",
      },
      loading: false, //表单提交按钮
      title: "",
      userList: [], //获取用户列表
      areaList: [], //省市区列表
      disabled: false, //查看编辑
    };
  },
  methods: {
    //获取地图数据
    handleSaveBmap(row) {
      let bMapForm = this.$refs.bmap.form;
      this.ruleForm.longitude = bMapForm.longitude;
      this.ruleForm.latitude = bMapForm.latitude;
      this.ruleForm.address = bMapForm.address;
      this.innerVisible = false
    },
    //获取高德地图省市区
    handleGetDistrict() {
      return new Promise((resolve, reject) => {
        axios({
          method: "GET",
          url: "https://restapi.amap.com/v3/config/district",
          dataType: "jsonp", //这里修改成jsonp
          params: {
            keywords: "中华人民共和国",
            subdistrict: "4",
            ak: "IjO56EW0Vq2gjagGOTyGr2Ug",
            extensions_code: 1,
          },
        })
          .then(function (response) {
            if (response.status == 200 && response.data.status == "1") {
              resolve(response.data.districts[0]["districts"]);
            } else {
              reject(response.data.info);
            }
          })
          .catch(function (error) {
            console.log(error);
          });
      });
    },
    popoverHide(checkedIds, checkedData) {
      if (!checkedData) return;
      this.ruleForm.addressCode = [
        checkedData.provinceCode,
        checkedData.cityCode,
        checkedData.regionCode,
        checkedData.code,
      ];
      console.log(checkedIds);
      console.log(checkedData);
    },
    //弹框关闭
    close() {
      this.dialog = false;
    },
    //获取角色列表
    handleGetUserList() {
      userList({ isPage: false }).then((res) => {
        if (res && res.success) {
          this.userList = res.data;
        }
      });
    },
    //选择管理员
    handleChooseAdmin() {
      this.ruleForm.adminMobile = this.userList.find((item) => {
        return item.name == this.ruleForm.adminName;
      })["mobile"];
    },
    //获取省列表数据
    handleGetProvinceList() {
      return new Promise((resolve, reject) => {
        areaApi.getProvinceList().then((res) => {
          if (res && res.success) {
            resolve(res.data);
          } else {
            reject(res.message);
          }
        });
      });
    },
    //获取省市区数据
    handleLocationsChange(val) {
      this.ruleForm.addressCode = JSON.parse(JSON.stringify(val));
      this.ruleForm = Object.assign({}, this.ruleForm);
    },
    //打开地图
    handleInnerVisible() {
      this.innerVisible = true;
      let _this = this;
      this.$nextTick(() => {
        if (_this.title == "新增医院机构") {
          _this.$refs.bmap.handleInit({});
        } else {
          _this.$refs.bmap.handleInit(_this.ruleForm);
        }
      });
    },
    //初始化弹框
    async showModal(_type, _row) {
      let _this = this;
      this.dialog = true;
      //获取用户列表
      this.handleGetUserList();

      this.disabled = false;
      this.ruleForm.addressCode = [];
      this.ruleForm.id = "";
      this.ruleForm.adminId = "";
      this.$nextTick(async (_) => {
        this.$refs.ruleForm.resetFields();
        _this.treeData = [];
        const { data } = await areaApi.getProvinceList();
        _this.treeData = data.map((item) => {
          item.children = [];
          return item;
        });
        if (_type == "edit") {
          _this.ruleForm = JSON.parse(JSON.stringify(_row));
          _this.ruleForm.adminId = _row.adminId;
          _this.ruleForm.adminName = _row.adminName
          _this.ruleForm.adminMobile = _row.adminMobile
          _this.ruleForm.addressCode = [
            _row.provinceCode,
            _row.cityCode,
            _row.regionCode,
            _row.townCode,
          ];
          _this.defaultCheckedKeys = [
            _row.townCode,
            _row.regionCode,
            _row.cityCode,
            _row.provinceCode,
          ];
          this.$refs.treeselect.handleInit(_this.treeData);

          this.title = "编辑医院机构";
        } else if (_type == "view") {
          this.ruleForm = JSON.parse(JSON.stringify(_row));
          this.ruleForm.adminId = _row.adminId;
          this.ruleForm.addressCode = [
            _row.provinceCode,
            _row.cityCode,
            _row.regionCode,
            _row.townCode,
          ];
          this.defaultCheckedKeys = [
            _row.townCode,
            _row.regionCode,
            _row.cityCode,
            _row.provinceCode,
          ];
          this.$refs.treeselect.handleInit(this.treeData);
          // this.$refs.bmap.handleInit(this.ruleForm);
          this.disabled = true;
          this.title = "查看医院机构";
        } else {
          this.title = "新增医院机构";
          this.ruleForm.addressCode = [];
          this.$refs.treeselect.handleInit(_this.treeData);
          // this.$refs.bmap.handleInit({});
        }
      });
    },
    handleInputChange() {
      this.$refs.amap.searchByHand(this.ruleForm.address);
    },
    //获取经纬度
    handleGetLatLong(row) {
      this.ruleForm.latitude = row.lat;
      this.ruleForm.longitude = row.lng;
    },
    //提交保存
    handleSave() {
      this.loading = true;
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          // let bMapForm = this.$refs.bmap.form;
          let params = {
            address: this.ruleForm.address, //详细地址
            shortName: this.ruleForm.shortName,
            adminMobile: this.ruleForm.adminMobile, //管理员电话
            adminName: this.ruleForm.adminName, //管理员名称
            cityCode: this.ruleForm.addressCode[1], //市编码
            code: this.ruleForm.code, //医院编码
            creditCode: this.ruleForm.creditCode,
            id: this.ruleForm.id,
            adminId: this.ruleForm.adminId,
            isFreeze: this.ruleForm.isFreeze,
            name: this.ruleForm.name, //医院名称
            provinceCode: this.ruleForm.addressCode[0], //省编码
            regionCode: this.ruleForm.addressCode[2], //区编码
            townCode: this.ruleForm.addressCode[3], //镇编码
            longitude: this.ruleForm.longitude,
            latitude: this.ruleForm.latitude,
          };
          hospitalApi
            .hospitalBaseSave(params)
            .then((res) => {
              if (res && res.success) {
                this.loading = false;
                this.dialog = false;
                this.$emit("getDataList");
              } else {
                this.loading = false;
              }
            })
            .catch((e) => {
              this.loading = false;
            });
        } else {
          this.loading = false;
        }
      });
    },
  },
};
</script>
<style lang="scss" scoped>
$dark_gray: #889aa4;
.show-pwd {
  position: absolute;
  right: 10px;
  font-size: 16px;
  color: $dark_gray;
  cursor: pointer;
  user-select: none;
}
#searchTip {
  position: relative;
  z-index: 15;
  top: 0;
  border: 1px solid #d7d8db;
}
</style>